package com.MartynovichIgor.KnowledgeTest.tools.usertools;

import com.MartynovichIgor.KnowledgeTest.tools.testtools.TestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by:
 * User: Igor Martynovich and Guzenko Igor
 * Date: 25.10.13
 */
public class UserAction {
    private User user;

    public UserAction(User user) {
        this.user = user;
    }

    /**
     * Метод обрабатывае вводимую пользователем строку.
     * @throws IOException
     */
    public void userActionHandler() throws IOException {
        History userHistory = user.getHistory();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int currentPosition = userHistory.getCurrentQuestion();
        while (currentPosition != TestController.COUNT_OF_QUESTIONS) {
            userHistory.printQuestion(currentPosition);
            String userAction = reader.readLine().toLowerCase();
            if (userAction.equals("exit")) {
                user.saveHistory();
                System.exit(0);
            }
            if (userAction.equals("undo")) {
                if (currentPosition == 0) {
                    currentPosition = 0;
                } else {
                    currentPosition--;
                }
                continue;
            }
            if (userAction.equals("")) {
                if (userHistory.getUserAnswer(currentPosition) == -1)
                    userHistory.setUserAnswer("0", currentPosition);
                currentPosition++;
                continue;
            }
            userHistory.setUserAnswer(userAction, currentPosition);
            currentPosition++;
        }
        user.saveHistory();
    }

    public int getUserScore() {
        return user.getScore();
    }
}
